package dao.impl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import model.impl.ConfigImpl;

import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.resotc.dao.ConfigDAO;
import org.resotc.model.Config;
import org.resotc.model.ElementType;
import org.resotc.model.Phasen;

public class ConfigDAOImpl extends AbstractXMLDAO implements ConfigDAO  {

	
	private final static String indexFileName = "config.xml";
	private List<Config> configs;
	
	public ConfigDAOImpl() throws JDOMException, IOException {
		indexFile = new File(rootPath + "/" + indexFileName);
		loadXML();

		parseXML();
	}
	
	
	
	
	
	private void parseXML() {
		configs = new LinkedList<Config>();

		Element rootElement = indexXMLInstance.getRootElement();

		List<Element> list = rootElement.getChildren();

		for (Element element : list) {
			int id = Integer.parseInt(element.getChildText("id"));
			ElementType type = ElementType.valueOf(element.getChildText("type").toUpperCase());
			Config config = null;
			if (type == ElementType.CENTROID)
			{
				int individualPerHour = Integer.parseInt(element.getChildText("ih"));
				String mode = "";
				mode = String.valueOf(element.getChildText("mode"));
				HashMap <Phasen,Integer> phasenlist = new HashMap<Phasen, Integer>();
				config = new ConfigImpl(id,type,individualPerHour,phasenlist,mode);
				configs.add(config);
			}
			else if (type == ElementType.INTERSECTION) {
				List<Element> phasen = element.getChild("phasen").getChildren();
				HashMap <Phasen,Integer> phasenlist = new HashMap<Phasen, Integer>();
				for (Element phase : phasen)
				{
					Phasen phasentyp = Phasen.valueOf(phase.getName().toUpperCase());
					int phasenzeit = Integer.valueOf(phase.getText().toUpperCase());
					phasenlist.put(phasentyp, phasenzeit);
					config = new ConfigImpl(id,type,0,phasenlist,"");
				}					
					configs.add(config);
			}
		}
	}




	/*
	 * (non-Javadoc)
	 * @see org.resotc.dao.ConfigDAO#getCentroidConfigs()
	 */
	public List<Config> getConfigs() {
		return this.configs;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.resotc.dao.ConfigDAO#getCentroidConfig(java.lang.Integer)
	 */
	public Config getConfig(Integer Id, ElementType type) {
		Config con= null;
		for (Config config : this.configs){
			if(config.getType() == type &&  config.getId() == Id)
			{
				con =  config;
			}
			else if(config.getType() == type &&  config.getId() == Id)
			{
				con = config;
			}
		}
		return con;
	}
}
